package com.cn.web.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cn.domain.Order;
import com.cn.domain.OrderItem;
import com.cn.domain.Product;
import com.cn.domain.User;

public class AddOrderServlet extends BaseServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		User user = (User) request.getSession().getAttribute("user");
		System.out.println(user);
		if(user==null){
			response.sendRedirect(request.getContextPath()+"/login.jsp");
			return;
		}
		Map<Product,Integer> map = (Map<Product, Integer>) request.getSession().getAttribute("cart");
		if(map==null){
			throw new RuntimeException("请先购物，选商品!");
		}
		Order o = new Order();
		String oid = UUID.randomUUID().toString();
		System.out.println(oid);
		o.setId(oid);
		System.out.println(oid);
		List<OrderItem> list = new ArrayList<OrderItem>();
		double total = 0;
		//将商品信息从session中的购物车中添加到OrderItem中
		for(Entry<Product,Integer> en:map.entrySet()){
			OrderItem oi = new OrderItem();
			int pid = en.getKey().getId();
			int buynum = en.getValue();
			oi.setOid(oid);
			oi.setPid(pid);
			oi.setBuynum(buynum);
			list.add(oi);
			total += buynum*en.getKey().getPrice();
		}
		String receiver = request.getParameter("receiver");
		String address = request.getParameter("address");
		String phone = request.getParameter("phone");
		if(receiver==null || "".equals(receiver.trim())||address==null || "".equals(address.trim())||phone==null || "".equals(phone.trim())){
			response.sendRedirect(request.getContextPath()+"/order.jsp");
			throw new RuntimeException("收货信息不能为空！");
		}
		o.setReceiver(receiver);
		o.setAddress(address);
		o.setPhone(phone);
		o.setStatu(0);
		o.setUid(user.getId());
		//o.setOrdertime(new Date());
		o.setSummoney(total);
		os.saveOrder(o, list);
		request.removeAttribute("cart");
		response.sendRedirect(request.getContextPath()+"/OrderListServlet");
	}

}
